import request from '@/axios';

let download = function(url, params, cb, method, extend = {}, fileName) {
  let temp = {
    method,
    url,
    ...extend
  };
  if (['POST'].includes(method.toUpperCase())) {
    temp.data = params;
  } else if (['GET'].includes(method.toUpperCase())) {
    temp.params = params;
  }
  request(temp).then(res => {
    if (res instanceof Blob) {
      try {
        res.text().then(t => {
          try { // 报错的时候，返回的就是json
            JSON.parse(t);
            cb && cb('fail', { msg: '系统异常，请稍后再试' });
          } catch (err) { // 没有报错返回的就是流数据，也就是try会失败，走到catch里面进行下载
            let objetUrl = URL.createObjectURL(res);
            let a = document.createElement('a');
            a.href = objetUrl;
            a.download = fileName;
            a.dispatchEvent(
              new MouseEvent('click', {
                bubbles: true,
                cancelable: true,
                view: document.defaultView
              })
            );
            cb && cb('succ', res);
          }
        });
      } catch (err) {
        let objetUrl = URL.createObjectURL(res);
        let a = document.createElement('a');
        a.href = objetUrl;
        a.download = fileName;
        a.dispatchEvent(
          new MouseEvent('click', {
            bubbles: true,
            cancelable: true,
            view: document.defaultView
          })
        );
        cb && cb('succ', res);
      }
    } else {
      cb && cb('fail', res);
    }
  }).catch(err => {
    cb && cb('fail', err);
  });
};

export default download;
